using B.S.XZYData.Api.Read.Application.Command.AssemblyWorkOrder;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;
using SqlSugar;

namespace B.S.XZYData.Api.Read.Application.Handler.AssemblyWorkOrder
{
    /// <summary>
    /// 查询装配工单处理器
    /// </summary>
    public class QueryAssemblyWorkOrderHandler : IRequestHandler<QueryAssemblyWorkOrderCommand, ApiResult<AssemblyWorkOrderPageResult>>
    {
        private readonly IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> _assemblyWorkOrderRepo;
        private readonly ILogger<QueryAssemblyWorkOrderHandler> _logger;

        public QueryAssemblyWorkOrderHandler(
            IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> assemblyWorkOrderRepo,
            ILogger<QueryAssemblyWorkOrderHandler> logger)
        {
            _assemblyWorkOrderRepo = assemblyWorkOrderRepo;
            _logger = logger;
        }

        public async Task<ApiResult<AssemblyWorkOrderPageResult>> Handle(QueryAssemblyWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<AssemblyWorkOrderPageResult>();
            try
            {
                var query = _assemblyWorkOrderRepo.GetAll().Where(x => !x.IsDeleted);

                // 单据编号查询
                if (!string.IsNullOrEmpty(request.DocumentNumber))
                {
                    query = query.Where(x => x.DocumentNumber.Contains(request.DocumentNumber));
                }

                // 工单数范围查询
                if (request.WorkOrderCountStart.HasValue)
                {
                    query = query.Where(x => x.WorkOrderCount >= request.WorkOrderCountStart.Value);
                }
                if ( request.WorkOrderCountEnd!=0)
                {
                    query = query.Where(x => x.WorkOrderCount <= request.WorkOrderCountEnd.Value);
                }

                // 已结束工单数范围查询
                if (request.FinishedWorkOrderCountStart.HasValue)
                {
                    query = query.Where(x => x.CompletedWorkOrderCount >= request.FinishedWorkOrderCountStart.Value);
                }
                if (request.FinishedWorkOrderCountEnd!=0)
                {
                    query = query.Where(x => x.CompletedWorkOrderCount <= request.FinishedWorkOrderCountEnd.Value);
                }

                // 创建时间范围查询
                if (request.CreationTimeStart.HasValue)
                {
                    query = query.Where(x => x.CreatorDate >= request.CreationTimeStart.Value);
                }
                if (request.CreationTimeEnd.HasValue)
                {
                    query = query.Where(x => x.CreatorDate <= request.CreationTimeEnd.Value);
                }

                // 应用排序
                query = ApplySorting(query, request.SortField, request.SortDirection);

                // 获取总记录数
                var totalCount = await query.CountAsync();

                // 分页查询
                var assemblyWorkOrderList = await query
                    .Skip((request.PageNumber - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var assemblyWorkOrderDtoList = assemblyWorkOrderList.Select(x => new AssemblyWorkOrderDto
                {
                    Id = x.Id,
                    DocumentNumber = x.DocumentNumber ?? "",
                    WorkOrderCount = x.WorkOrderCount ?? 0,
                    FinishedWorkOrderCount = x.CompletedWorkOrderCount ?? 0,
                    DocumentProgress = x.DocumentProgress ?? 0,
                    Remarks = x.Remarks,
                    CreatorDate = x.CreatorDate,
                    Creator = x.Creator,
                    UpdatorDate = x.UpdatorDate,
                    Updator = x.Updator
                }).ToList();

                var result = new AssemblyWorkOrderPageResult
                {
                    TotalCount = totalCount,
                    Data = assemblyWorkOrderDtoList,
                    PageNumber = request.PageNumber,
                    PageSize = request.PageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / request.PageSize)
                };

                res.Data = result;
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询装配工单异常：{ex.Message}");
                res.Msg = "查询装配工单异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.AssemblyWorkOrder> ApplySorting(
            ISugarQueryable<Domain.ZSHH.AssemblyWorkOrder> query,
            string sortField,
            string sortDirection)
        {
            switch (sortField.ToLower())
            {
                case "documentnumber":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.DocumentNumber)
                        : query.OrderByDescending(x => x.DocumentNumber);

                case "creatordate":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.CreatorDate)
                        : query.OrderByDescending(x => x.CreatorDate);

                default:
                    // 默认按Id倒序
                    return query.OrderByDescending(x => x.Id);
            }
        }
    }
} 